<template>
  <div class="technologyManage-scheme-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <div class="tree-container">
        <div class="search-content">
          <el-input
            placeholder="请输入"
            v-model.trim="filterText"
            suffix-icon="el-icon-search"
            @input="handleInput">
          </el-input>
          <div class="btns">
            <span class="icon">
              <i :class="['el-icon-arrow-up', expandAll ? 'open' : 'close']" @click="toggle"></i>
            </span>
            <span class="icon" v-if="hasTreeAdd">
              <i class="el-icon-plus" @click="addArea"></i>
            </span>
          </div>
        </div>
        <el-tree
          :data="treeData"
          :default-expand-all="expandAll"
          :current-node-key="selectKey"
          :indent="10"
          node-key="id"
          ref="tree"
          :highlight-current="true"
          :props="defaultProps"
          @node-click="handleNodeClick"
          :filter-node-method="filterNode">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="label" :title="node.label">{{ node.label }}</span>
            <span class="btns">
              <i v-if="hasTreeEdit" class="el-icon-edit-outline" @click="editArea(data)"></i>
              <i v-if="hasTreeDel" class="el-icon-delete" @click="delArea(data)"></i>
            </span>
          </span>
        </el-tree>
      </div>
      <div class="table-container">
        <div class="search-container">
          <div class="search-content">
            <el-input
              class="search-input"
              placeholder="图纸名称|专业名称|上传人"
              v-model="condition"
              suffix-icon="el-icon-search"
              @blur="handleSearch"
              @keydown.native.enter="handleSearch">
            </el-input>
            <el-button icon="el-icon-search" type="primary" @click="handleSearch">
              搜索
            </el-button>
            <el-button type="primary" icon="el-icon-refresh" @click="handleRefresh">
              重置
            </el-button>
          </div>
        </div>
        <div class="table-btns">
          <h4 class="title">图纸管理</h4>
          <div class="btns">
            <el-button
              v-if="hasTabAdd"
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd">新增</el-button>
          </div>
        </div>
        <el-table
          class="table-content"
          v-loading="tableLoading"
          element-loading-custom-class="custom-load"
          :data="tableData"
          row-key="id">
          <el-table-column label="序号" type="index" width="80"></el-table-column>
          <el-table-column prop="fileName" label="方案名称" width="300" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="prim-btn" @click="handleView(scope.row)">
                {{ scope.row.fileName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="majorName" label="方案分组"></el-table-column>
          <el-table-column prop="modifyTime" label="上传日期"></el-table-column>
          <el-table-column prop="createrUserName" label="上传人"></el-table-column>
          <el-table-column prop="qrCode" label="二维码">
            <template slot-scope="scope">
              <el-image
                v-if="scope.row.qrCodeUrl"
                class="qr-img"
                lazy
                :scroll-container="scrollDom"
                :src="scope.row.qrCodeUrl"
                :preview-src-list="[scope.row.qrCodeUrl]">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240">
            <template slot-scope="scope">
              <span style="display: none"></span>
              <span
                v-if="hasTableDownLoad"
                class="prim-btn"
                @click="downloadFile(scope.row)">下载</span>
              <span
                v-if="hasTableEdit"
                class="prim-btn"
                @click="handleEdit(scope.row)">编辑</span>
              <span
                v-if="hasTableDetail"
                class="prim-btn"
                @click="setDetail(scope.row)">查看</span>
              <span
                v-if="hasTableDel"
                class="dar-btn"
                @click="hanldeDelete(scope.row)">删除</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="total > 10"
          :page-size="pageSize"
          :current-page="pageNo"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </main>
    <add-area
      :visible="areaVisible"
      :loading="areaLoading"
      :type="areaType"
      :menus="treeData"
      :options="currentAreaData"
      @cancel="areaVisible = false"
      @submit="handleSaveArea">
    </add-area>
    <add-scheme
      :visible="visible"
      :loading="loading"
      :type="type"
      :menus="treeData"
      :options="currentData"
      @cancel="visible = false"
      @submit="handleSave">
    </add-scheme>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import addArea from '@/components/project/technologyManage/addArea';
import addScheme from '@/components/project/technologyManage/addScheme';

// 安全检查-隐患排查及治理
export default {
  components: {
    addArea,
    addScheme,
    Breadcrumb,
  },
  data() {
    return {
      breadcrumbData: [
        {
          name: '技术管理',
        },
        {
          name: '施工方案'
        }
      ],
      expandAll: true,
      // 内容搜索项
      condition: '',
      filterText: '',
      treeData: [],
      majorType: '2',
      currentRoles: null,
      selectKey: '',
      defaultProps: {
        children: 'children',
        label: 'majorName'
      },
      scrollDom: null,
      tableLoading: false,
      tableData: [],
      total: 0,
      pageSize: 10,
      pageNo: 1,
      loading: false,
      visible: false,
      type: 'add',
      currentData: {},
      // 文件节点设置
      areaType: 'add',
      areaVisible: false,
      areaLoading: false,
      currentAreaData: {},
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userId() {
      return this.$store.state.userInfo.uuid;
    }
  },
  created() {
    this.getTechTree();
    this.getTableData();
  },
  mounted() {
    this.scrollDom = document.querySelector('.el-table__body-wrapper');
  },
  methods: {
    // 获取列表数据
    async getTableData() {
      const params = {
        condition: this.condition || '',
        majorId: this.selectKey,
        fileType: '2', // 1：图纸；2：施工
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        projectId: this.projectId,
      };
      this.tableLoading = true;
      const { success, data: {
        data
      }} = await this.$Model.getTechFileList(params);
      this.tableLoading = false;
      if (success && data) {
        const list = data.list || [];
        this.total = data.total || 0;
        this.tableData = list.map(item => {
          const { qrCode } = item;
          return {
            qrCodeUrl: this.$checkUrl(qrCode),
            ...item
          };
        });
      }
    },
    // 获取技术管理树
    async getTechTree() {
      const { success, data: {
        data
      }} = await this.$Model.getTechTree({
        majorType: this.majorType,
        projectId: this.projectId
      });
      if (success) {
        this.treeData = data || [];
        if (this.selectKey) {
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.selectKey , true);
          });
        }
      }
    },
    handleSearch() {
      this.clear();
      this.getTableData();
    },
    handleRefresh() {
      this.clear();
      this.condition = '';
      this.getTableData();
    },
    handleInput(val) {
      this.$refs.tree && this.$refs.tree.filter(val);
    },
    toggle() {
      this.expandAll = !this.expandAll;
      try {
        this.changeTreeNodeStatus(this.$refs.tree.store.root);
      } catch (e) {}
    },
    // 改变节点的状态
    changeTreeNodeStatus(node) {
      node.expanded = this.expandAll;
      for (let i = 0; i < node.childNodes.length; i++) {
        // 改变节点的自身expanded状态
        node.childNodes[i].expanded = this.expandAll;
        // 遍历子节点
        if (node.childNodes[i].childNodes.length) {
          this.changeTreeNodeStatus(node.childNodes[i]);
        }
      }
    },
    /**
     * 选中当前文件
     * @param data {Object} 当前节点数据
     * @param node 节点
     */
    handleNodeClick(data, node) {
      const { id } = data;
      this.selectKey = this.selectKey === id ? '' : id;
      !this.selectKey && this.$refs.tree.setCurrentKey(null , true);
      this.condition = '';
      this.clear();
      this.getTableData();
    },
    // 过滤节点
    filterNode(value, data) {
      if (!value) return true;
      return data.majorName.indexOf(value) !== -1;
    },
    // 清除参数
    clear() {
      this.pageNo = 1;
      this.pageSize = 10;
      this.total = 0;
      this.tableLoading = false;
      this.tableData = [];
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getTableData();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getTableData();
    },
    // 新增节点
    addArea() {
      this.areaType = 'add';
      this.currentAreaData = {};
      this.areaLoading = false;
      this.areaVisible = true;
    },
    // 编辑节点
    editArea(data) {
      this.areaType = 'edit';
      this.currentAreaData = { ...data };
      this.areaLoading = false;
      this.areaVisible = true;
    },
    // 删除节点
    delArea(data) {
      this.$confirm('此操作将删除该条数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.delTechTree({
          id: data.id
        });
        if (success) {
          if (this.selectKey === data.id) {
            this.selectKey = '';
            this.$refs.tree.setCurrentKey(null , true);
          }
          this.$message.success('删除成功');
          this.getTechTree();
        }
      });
    },
    // 保存节点
    async handleSaveArea(data) {
      const params = {
        majorType: this.majorType,
        projectId: this.projectId,
        ...data
      };
      const hasAdd = this.areaType === 'add' ||
        (this.currentAreaData.parentId === '0' &&
          this.currentAreaData.parentId !== params.parentId);
      if (!params.parentId) delete params.parentId;
      if (!params.id) delete params.id;
      this.areaLoading = true;
      const { success } = hasAdd
        ? await this.$Model.addTechTree(params)
        : await this.$Model.updateTechTree(params);
      this.areaLoading = false;
      if (success) {
        this.$message.success('保存成功');
        this.getTechTree();
        this.areaVisible = false;
      }
    },
    handleView({ fileUrl }) {
      fileUrl && window.open(this.$checkUrl(fileUrl));
    },
    // 下载
    downloadFile(row) {
      this.$fileToUpload(row.fileUrl);
    },
    // 新增
    handleAdd() {
      this.type = 'add';
      this.currentData = {};
      this.loading = false;
      this.visible = true;
    },
    // 编辑
    handleEdit(row) {
      this.type = 'edit';
      this.currentData = { ...row };
      this.loading = false;
      this.visible = true;
    },
    setDetail(row) {
      this.type = 'detail';
      this.currentData = { ...row };
      this.loading = false;
      this.visible = true;
    },
    // 删除
    hanldeDelete(row) {
      this.$confirm('此操作将删除该方案, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.delTechFile({
          ids: row.id
        });
        if (success) {
          this.$message.success('删除成功');
          this.tableData.length < 2 && this.clear();
          this.getTableData();
        }
      });
    },
    // 保存
    async handleSave(data) {
      const params = {
        projectId: this.projectId,
        ...data
      };
      if (!params.id) delete params.id;
      this.loading = true;
      const { success } = this.type === 'add'
        ? await this.$Model.addTechFile(params)
        : await this.$Model.updateTechFile(params);
      this.loading = false;
      if (success) {
        this.$message.success('保存成功');
        this.getTableData();
        this.visible = false;
      }
    },
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';

  .technologyManage-scheme-page {
    width: 100%;
    height: 100%;
    background-color: $baseBg;
    color: #fff;
    main {
      width: 100%;
      height: calc(100% - 40px);
      padding: 20px;
      display: flex;
      justify-content: space-between;
      border-radius: 10px;
      .tree-container {
        width: 400px;
        height: 100%;
        padding: 20px;
        border-radius: 20px;
        background-color: $mainBg;
        .search-content {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
          position: relative;
          .btns {
            margin: 0 5px;
            display: flex;
            align-items: center;
            .icon {
              display: inline-block;
              margin-left: 10px;
              width: 35px;
              height: 35px;
              text-align: center;
              line-height: 35px;
              background-color: rgba(160, 164, 179, 0.4);
              border-radius: 5px;
              cursor: pointer;
              i {
                font-size: 20px;
                transition: transform .3s, color .2s;
                &:hover {
                  color: $lightBtnBg;
                }
                &.close {
                  transform: rotateZ(180deg);
                }
              }
            }
          }
        }
        .el-tree {
          background: $mainBg;
          color: #fff;
          /deep/ .el-tree-node__content {
            height: 40px;
            &:hover {
              color: $mainColor;
              background: transparent;
            }
            .custom-tree-node {
              width: 100%;
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding-right: 5px;
              &:hover {
                .btns {
                  visibility: visible;
                  opacity: 1;
                }
              }
              .label {
                flex: 1;
                width: calc(100% - 100px);
                display: inline-block;
                overflow: hidden;
                text-overflow: ellipsis;
              }
              .btns {
                visibility: hidden;
                opacity: 0;
                transition: all .2s;
                i {
                  font-size: 18px;
                  cursor: pointer;
                }
              }
            }
          }
        }
        .el-tree {
          /deep/ .el-tree-node.is-current > .el-tree-node__content {
            color: $mainColor;
            background: $baseBg;
            .custom-tree-node {
              .btns {
                visibility: visible;
                opacity: 1;
              }
            }
          }
          /deep/ .el-tree-node.is-focusable:not(.is-current) > .el-tree-node__content {
            background: transparent;
          }
        }
      }
      .table-container {
        width: calc(100% - 420px);
        height: 100%;
        background-color: $mainBg;
        padding: 10px 20px;
        border-radius: 20px;
        overflow: hidden;
        .search-container {
          width: 100%;
          height: 80px;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .search-content {
            width: 600px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .search-input {
              width: 300px;
              margin-right: 20px;
            }
          }
        }
        .table-btns {
          width: 100%;
          height: 80px;
          position: relative;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 5px;
          .btns {
            display: flex;
            align-items: center;
          }
        }
        .table-content {
          width: 100%;
          height: calc(100% - 200px);
          /deep/ .el-table__body-wrapper {
            height: 100%;
            padding-bottom: 46px;
            overflow-y: auto;
            .qr-img {
              width: 30px;
              cursor: pointer;
            }
          }
          .img-contianer {
            width: 100px;
            height: 60px;
            position: relative;
            .img-icon {
              position: absolute;
              bottom: -2px;
              right: 0;
              font-size: 24px;
              color: $mainColor;
              span {
                position: absolute;
                top: calc(50% - 8px);
                left: calc(50% - 4px);
                font-weight: bold;
                font-size: 16px;
              }
            }
          }
          /deep/ .img {
            width: 100px;
            height: 60px;
          }
          .iconfont {
            cursor: pointer;
          }
        }
      }
    }
  }
</style>
